import 'package:flutter/material.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

import '../../../hj_model/video_model.dart';
import '../../../tools_base/widget/net_image_widget.dart';

class VideoCacheCell extends StatefulWidget {
  final VideoModel? videoModel;
  final bool isCacheEdit; // 缓存编辑状态
  final GestureTapCallback? onCacheTap;
  final Widget? child;

  const VideoCacheCell({
    Key? key,
    this.videoModel,
    this.isCacheEdit = false,
    this.onCacheTap,
    this.child,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _VideoCacheCellState();
  }
}

class _VideoCacheCellState extends State<VideoCacheCell> {
  int maxTopCount = 4;

  String get cacheStatusDesc {
    if (realModel.progress >= 1) {
      return "已完成";
    } else if (realModel.isLoaderRunning == "1") {
      return "正在加载中...";
    } else {
      return "已暂停";
    }
  }

  bool get isCacheFinished => realModel.progress >= 1;
  VideoModel? _realModel;

  VideoModel get realModel {
    if (_realModel != null) return _realModel!;
    VideoModel? realM;
    if (widget.videoModel != null) {
      realM = widget.videoModel;
    } else {
      realM ??= VideoModel();
    }
    _realModel = realM;
    return _realModel!;
  }

  @override
  void didUpdateWidget(covariant VideoCacheCell oldWidget) {
    if (oldWidget.videoModel?.id != widget.videoModel?.id) {
      _realModel = null;
    }
    super.didUpdateWidget(oldWidget);
  }

  void _isCacheEditEvent() {
    realModel.isSelected = !realModel.isSelected;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: [
        Container(
          decoration: BoxDecoration(
            color: const Color(0xff151515),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: widget.child ??
                    VideoSimpleCellWidget(
                      videoModel: widget.videoModel,
                      textLines: 1,
                      imgBorderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8),
                        topRight: Radius.circular(8),
                      ),
                    ),
              ),
              _buildCacheStatus(realModel),
            ],
          ),
        ),
        _buildCacheButton(realModel),
      ],
    );
  }

  Widget _buildCacheStatus(VideoModel model) {
    return Container(
      padding: const EdgeInsets.only(top: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 3),
          Text(
            cacheStatusDesc,
            textAlign: TextAlign.left,
            style: const TextStyle(fontSize: 11, color: Color(0xffd43f61), height: 1.5),
          ),
          Container(
            height: 14,
            child: Opacity(
              opacity: (cacheStatusDesc != "已完成") ? 1 : 0,
              child: Row(
                children: [
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(2),
                      child: LinearProgressIndicator(
                        value: widget.videoModel?.progress,
                        backgroundColor: const Color(0xff727272),
                        color: const Color(0xffe75160),
                      ),
                    ),
                  ),
                  const Padding(padding: EdgeInsets.only(left: 5)),
                  Text(
                    "${widget.videoModel?.loadProgress ?? "0.00"}%",
                    textAlign: TextAlign.left,
                    style: const TextStyle(fontSize: 11, color: Color(0xffaab2b7), height: 1.2),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildCacheButton(VideoModel videoModel) {
    if (widget.isCacheEdit) {
      return _buildCacheEditButton();
    }
    if (isCacheFinished) {
      return Container();
    }
    return Container(
      decoration: BoxDecoration(color: Colors.black.withOpacity(.1), borderRadius: BorderRadius.circular(8)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: widget.onCacheTap,
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(bottom: 72),
              child: Container(
                width: 120,
                height: 42,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.8),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      (videoModel.isLoaderRunning == "1") ? "cache_stop.webp".videoPath : "cache_start.webp".videoPath,
                      width: 15,
                      height: 17,
                      fit: BoxFit.cover,
                    ),
                    const Padding(padding: EdgeInsets.only(left: 6)),
                    Text(
                      (videoModel.isLoaderRunning == "1") ? "结束缓存" : "开始缓存",
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCacheEditButton() {
    return InkWell(
      onTap: _isCacheEditEvent,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: const Color(0x99707070),
        ),
        child: Center(
          child: Image.asset(
            widget.videoModel?.isSelected == true ? "cache_selected.webp".videoPath : "cache_unselected.webp".videoPath,
            width: 40,
            height: 40,
          ),
        ),
      ),
    );
  }

  // @override
  // void dispose() {
  //   PaintingBinding.instance.imageCache.clear();
  //   super.dispose();
  // }
}

class VideoACGCacheCell extends StatelessWidget {
  final VideoModel? videoModel;

  VideoACGCacheCell({this.videoModel});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: NetworkImageLoader(
            imageUrl: (videoModel?.mediaInfo?.verticalCover ?? '').isNotEmpty
                ? videoModel?.mediaInfo?.verticalCover ?? ''
                : videoModel?.mediaInfo?.horizontalCover ?? '',
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
        ),
        4.sizeBoxH,
        Text(
          videoModel?.title ?? '',
          style: const TextStyle(fontSize: 14, color: Colors.white),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.left,
        ),
        4.sizeBoxH,
        Text(
          '${videoModel?.getUpdateString()} · 共${videoModel?.totalEpisode ?? 0}话',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 12,
            color: videoModel?.updateStatus == 2 ? Color(0xff757575) : Color(0xffEEC76B),
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }
}
